package com.yao.springcloud;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.config.client.ConfigClientProperties;
import org.springframework.cloud.config.client.ConfigClientProperties.Discovery;
import org.springframework.cloud.config.client.ConfigServerInstanceProvider;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RefreshScope
@SpringBootApplication
public class ConfigClientApplication {

	private static final Logger logger = LoggerFactory.getLogger(ConfigClientApplication.class);

	@Value("${spring.application.name}")
	private String servername;

	@Value("${server.port}")
	private String port;

	public static void main(String[] args) {
		
		SpringApplication.run(ConfigClientApplication.class, args);
//		SpringApplication app = new SpringApplication(ConfigClientApplication.class);
//		app.addListeners(new MyListener());
//		app.addListeners((ApplicationEnvironmentPreparedEvent e) -> logger.info("==文件内容发送改变=="));
		
		
		//文件夹监听
		try {
			Path path = Paths.get("E:\\sts_workspace\\config-server");
			System.out.println(path);
			final WatchService watchService = path.getFileSystem().newWatchService();
			path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
			System.out.println("Report any file changed within next 1 minutes...");
			
			final WatchKey watchKey = watchService.take();/*poll(10, TimeUnit.SECONDS);*/
			while(watchKey != null) {
				new ServiceConfigHelper();
			    watchKey.pollEvents().stream().forEach(event -> {});
//			    /*System.out.println(event.context()+ " -0 "+ServiceConfigHelper.getServiceConfigValue("logger")*/));
			}
			
		} catch (IOException | InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
//		app.run(args);
		
//		SpringApplication.run(ConfigClientApplication.class, args);
	}

	@Autowired
	private DiscoveryClient client;

	@Autowired
	private ConfigClientProperties clientProperties;

	private ConfigServerInstanceProvider serverInstanceProvider;

	@RequestMapping(value = "/getServer")
	public void getProperty() {
		List<String> services = client.getServices();
		System.out.println("====getserver====" + services);
		for (String string : services) {
			System.out.println(string);
		}
		Discovery discovery = clientProperties.getDiscovery();
		System.out.println("serviceId = " + discovery.getServiceId());

		Map<String, String> map = clientProperties.getHeaders();
		for (String key : map.keySet()) {
			System.out.println(key + " : " + map.get(key));
		}
		System.out.println(clientProperties.getUri());

		/*
		 * ServiceInstance instance =
		 * serverInstanceProvider.getConfigServerInstance(discovery.getServiceId());
		 * Map<String, String> data = instance.getMetadata();
		 * 
		 * System.out.println("data : "); for (String key : data.keySet()) {
		 * System.out.println(key +" : "+ map.get(key)); }
		 */

		// ServiceInstance serverInstance = new
		// ConfigServerInstanceProvider().getConfigServerInstance("");
	}

	@Bean
	public CommandLineRunner runner() {
		logger.info("===========服务[{} {}]启动完成===========", servername, port);
		logger.info(testlogger());
		return null;
	}

	@Value("${version}")
	String version;

	@Value("${apiservice.miResource.url}")
	private String resourceUri;

	@RequestMapping(value = "hi")
	public String hi() {
		String msg = String.format(
				"Refresh configuration with RabbitMQ. And current [%s:%s] %nVersion is : %s. %nAnd current uri = %s",
				servername, port, version, resourceUri);
		System.out.println("++testlogger++ " + testlogger());
		return msg;
	}

	@RequestMapping(value = "getProperty", method = RequestMethod.GET)
	public String get(@RequestParam String key) {
		return "读取properties文件属性结果为：  " + ServiceConfigHelper.getServiceConfigValue(key);
	}

	@Autowired
	BaseProperty baseProperty;

	@RequestMapping(value = "property")
	public String property() {
		System.out.println("===============输入property属性====================");
		return baseProperty.toString();
	}

	@Autowired
	PropertiesTest properties;

	public String testlogger() {
		return properties.toString();
	}

}
